package dmwr.servlet;

import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dmwr.Dmwr;
import dmwr.bean.User;
import dmwr.service.Service.Duplicate;
import dmwr.util.Passwords;
import dmwr.web.Http;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(Login.class.getName());

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = Http.request().getParameter("username");
		String password = Http.request().getParameter("password");
		String remember = Http.request().getParameter("remember");
		char[] passwordChars = password.toCharArray();
		for (int i = 0; i < passwordChars.length; i++) {
			passwordChars[i] = '*';
		}
		log.info("username = " + username + ", password = "
				+ String.valueOf(passwordChars));
		if (username != null && username.length() > 0 && password != null
				&& password.length() > 0) {
			User user = Dmwr.service().getUser(username);
			log.info("user = " + user);
			if (user != null
					&& Passwords.check(password.toCharArray(),
							user.getPasswordSalt(), user.getPasswordHash())) {
				if ("true".equals(remember)) {
					String cookieValue = user.getUsername() + ' '
							+ UUID.randomUUID().toString();
					user.setRememberSalt(Passwords.salt());
					user.setRememberHash(Passwords.hash(
							cookieValue.toCharArray(), user.getRememberSalt()));
					try {
						Dmwr.service().saveUser(user);
					} catch (Duplicate e) {
						throw new ServletException(e);
					}
					Cookie cookie = new Cookie("remember", cookieValue);
					String contextPath = Http.request().getContextPath();
					cookie.setPath(contextPath != null
							&& contextPath.length() > 0 ? contextPath : "/");
					cookie.setMaxAge(30 * 24 * 60 * 60);
					Http.response().addCookie(cookie);
				}
				Http.request().getSession().setAttribute("user", user);
				Http.redirect("/");
				return;
			}
		}
		Http.forward("/login.jsp");
	}
}
